# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from iccec.rules import *
from zc_core.dao.sku_dao import SkuDao
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.done_filter import DoneFilter
from datetime import datetime
from scrapy.utils.project import get_project_settings
from iccec.utils.login import SeleniumLogin
from zc_core.spiders.base import BaseSpider


class FullSpider(BaseSpider):
    name = 'full_supplier'

    # 商品详情
    item_url = 'https://emi.iccec.cn/apis/emi/cc/users/signup/querySkuPrice'
    # 商品价格
    goods_price_url = 'https://emi.iccec.cn/apis/emi/cc/users/signup/querySkuPrice'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)
        # self.cookies = SeleniumLogin().get_cookies()
        self.cookies_str = 'DSESSIONID=ZT-067b372f-9f67-4fa6-98ed-5e5372ceb26e; access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE5NDY2OTg2MzEsInVzZXJfbmFtZSI6IjEzMzI4MDU5NTEwIiwianRpIjoiMGUxNGI0YjktNjY4Yy00YWQwLWE3ZmQtZDEwZGU3YjEwOTdmIiwiY2xpZW50X2lkIjoicmVzb3VyY2UxIiwic2NvcGUiOlsicmVhZCJdfQ.KUgRuaJYyyO2Nru0MgR-_1KS1H8znCTYBZUUiGaISEOOgVatGAsPsWwym8Rk13NzGWazQWZfDxnmS6FECKD-68SiFY9inKSOis8-pGZ2SnGRyzffLaPicIwuKV9iK6WI_4NFbifQDgDMXEkQMnxkJdTdBNfiacGY3AT6kkJ2nRQ; refresh_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzg2MTA2MzEsInVzZXJfbmFtZSI6IjEzMzI4MDU5NTEwIiwianRpIjoiYWUxYmMxOWEtNGU5Yi00YWZmLWI1ZTItZDk5ODdkMjlhYmUwIiwiY2xpZW50X2lkIjoicmVzb3VyY2UxIiwic2NvcGUiOlsicmVhZCJdLCJhdGkiOiIwZTE0YjRiOS02NjhjLTRhZDAtYTdmZC1kMTBkZTdiMTA5N2YifQ.aFOZUQ7pylpjNkS2F7m__edumHlne9V4acnl2hKBSj9UvgaYZDMh8tBayXXterAT37MTnTsquiZf4EenetRR57IJbeoHZU7KxZwrTwo6J7qPhPU6WUy-ylckysAjRL4EZ-rQQ_uM9KTnU1j0Y1mi0hR4_uVcBaWICF0Jh8UhKt0; topNavMsg={%22todoCount%22:%220%22%2C%22messageCount%22:%220%22}; acw_tc=276aedd016356586723234023e60cfd722c7dd94a8d77967f86283f68c9b3b; topNavTimer={%22time%22:1635658694.483}'
        self.cookies = {item.split('=')[0]: item.split('=')[1] for item in
                        self.cookies_str.split(';')}

    def _build_list_req(self, sku_id,
                        supplierName, supplierId, skuImg, originPrice, salePrice, barCode, spuId):
        return Request(url=self.item_url,
                       method='POST',
                       meta={
                           'reqType': 'item',
                           'batchNo': self.batch_no,
                           'skuId': sku_id,
                           'supplierName': supplierName,
                           'supplierId': supplierId,
                           'skuImg': skuImg,
                           'originPrice': originPrice,
                           'salePrice': salePrice,
                           'barCode': barCode,
                           'spuId': spuId
                       },
                       dont_filter=True,
                       headers={
                           'Content-Type': 'application/json;charset=UTF-8'
                       },
                       body=json.dumps({"skuId": sku_id, "indexType": 0, "agentId": 100019}),
                       callback=self.parse_item_data,
                       errback=self.error_back,
                       cookies=self.cookies
                       )

    def start_requests(self):

        settings = get_project_settings()
        # while_list = settings.get("CATALOG_WHITE_LIST")
        pool_list = SkuDao().get_batch_sku_list(self.batch_no, query={"clickCount": {"$gt": 0}}, fields={"_id": 1,
                                                                                                         "offlineTime": 1,
                                                                                                         'supplierId': 1,
                                                                                                         'supplierName': 1,
                                                                                                         'skuImg': 1,
                                                                                                         'originPrice': 1,
                                                                                                         'salePrice': 1,
                                                                                                         'barCode': 1,
                                                                                                         'spuId': 1})
        self.logger.info('全量：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            supplierId = sku.get('supplierId')
            supplierName = sku.get('supplierName')
            originPrice = sku.get('originPrice')
            salePrice = sku.get('salePrice')
            barCode = sku.get('barCode')
            skuImg = sku.get('skuImg')
            spuId = sku.get('spuId')
            offline_time = sku.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            # 采集商品
            yield self._build_list_req(sku_id, supplierName, supplierId, skuImg, originPrice, salePrice, barCode,
                                       spuId)

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        data = parse_supplier_item_data(response)
        self.logger.info('商品: [%s]' % data.get('skuId'))
        yield Request(
            url=self.goods_price_url,
            method='POST',
            meta={
                'reqType': 'item',
                'batchNo': self.batch_no,
                'item': data
            },
            dont_filter=True,
            headers={
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body=json.dumps({"skuId": sku_id, "indexType": 0, "agentId": 100019}),
            callback=self.patse_item_price_data,
            errback=self.error_back,
            cookies=self.cookies
        )

    def patse_item_price_data(self, response):
        meta = response.meta
        item = meta.get('item')
        json_data = json.loads(response.text)
        sale_price = json_data.get('data', {}).get('salePrice')
        item['salePrice'] = sale_price
        yield item
